import { CacheOption, BdjfRequest, RequestOption } from './type';

export class RequestImpl implements BdjfRequest {
    public requestOption: RequestOption;
    public cacheOption?: CacheOption | undefined;

    constructor(requestOption: RequestOption, cacheOption?: CacheOption) {
        this.requestOption = requestOption;
        this.cacheOption = cacheOption;
    }
    public closeLoading = (): BdjfRequest => {
        this.requestOption.hideLoading = true;
        return this;
    }

    public openLoading = () => {
        this.requestOption.hideLoading = false;
        return this;
    }

    public setOption = (newOption: RequestOption): BdjfRequest => {
        Object.keys(newOption).forEach((key) => {
            this.requestOption[key] = newOption[key];
        });
        return this;
    }
    public setCacheOption = (newOption: CacheOption): BdjfRequest => {
        if (this.cacheOption) {
            Object.keys(newOption).forEach((key) => {
                this.cacheOption![key] = newOption[key];
            });
        } else {
            this.cacheOption = newOption;
        }
        return this;
    }



    public conflictCacheUrl = (): string[] => {
        // 将数组中的 RequestBean 的url属性抽取出来作为一个数组返回
        return this.cacheOption?.conflictCacheUrl?.map((request) => {
            return request.requestOption.url;
        }) || [];
    }
}

export function createRequest(requestOption: RequestOption, cacheOption?: CacheOption) {
    return new RequestImpl(requestOption, cacheOption);
}
